#!/usr/bin/env python

import time

import schedule

from .DirectVideoSource import DirectVideoSource
from .VideoDownloader import VideoDownloader
from .VideoUploader import VideoUploader
from .table import Video, Post, DBSession

downloader = VideoDownloader()

uploader = VideoUploader()

source = DirectVideoSource("186308899", "268536810", "14086388", "22603735")

# you_get.main("")

def process():
    session = DBSession()
    try:
        for link in source.get():
            dedupRecord = session.query(Video).filter(Video.link == link).first()
            if dedupRecord:
                continue
            video = downloader.downloader(link)
            if video:
                session.add(video)
                session.commit()
                uploader_info = uploader.upload(video)
                if uploader_info:
                    session.add(
                        Post(vid=video.id, site="youtube", link=uploader_info.targetUrl, acount=uploader_info.acount))
                    session.commit()
                    print("upload link: %s to youtube: %s, use account:%s " % (
                        link, uploader_info.targetUrl, uploader_info.acount))
    except Exception as e:
        print(e)

    session.close()


def main(**kwargs):
    """Main entry point.
    you-get (legacy)
    """
    print("hello world")
    print(kwargs)

    # you_get.main(**kwargs)

    # videoDao.createTable()

    schedule.every(60).minutes.do(process).run()

    while True:
        schedule.run_pending()
        time.sleep(1)


if __name__ == '__main__':
    main()
